#ifndef MODBUSTCP_H
#define MODBUSTCP_H

#include <QObject>

#include <QModbusTcpClient>
#include <QModbusRtuSerialMaster>
#include <QModbusDataUnit>
#include <QStandardItemModel>
#include <QUrl>
#include <QtSerialPort/QSerialPort>
#include <QBitArray>
#include <QDebug>

#include "modbus.h"

class QModbusClient;
class QModbusReply;

enum {
    NumColumn = 0,
    CoilsColumn = 1,
    HoldingColumn = 2,
    ColumnCount = 3,
    RowCount = 10
};

class ModbusTcp : public QObject
{
    Q_OBJECT
public:

    struct Settings {
        int parity = QSerialPort::EvenParity;
        int baud = QSerialPort::Baud19200;
        int dataBits = QSerialPort::Data8;
        int stopBits = QSerialPort::OneStop;
        int responseTime = 1000;
        int numberOfRetries = 3;
    };

    explicit ModbusTcp(QObject *parent = 0);

    bool connectToHost(QString type, QUrl url);

    bool disconnectToHost();

    bool readData(int type);
    void readReady();

    void getCoilsData(int address, quint8 data);
    void getHoldingRegistersData(int address, quint16 data);

    bool writeData(int type);

signals:

public slots:

private:
    QModbusReply *lastRequest;
    //QModbusClient *modbusDevice;

    QModbusTcpClient modbusDevice;

    Settings m_settings;
    int server_address = 1;
    QBitArray m_coils;
    QVector<quint16> m_holdingRegisters;

    QModbusDataUnit readRequest(int type) const;
    QModbusDataUnit writeRequest(int type) const;

};

#endif // MODBUSTCP_H
